package com.qdsgjsfk.vision.ui.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.qdsgjsfk.vision.R;

import com.qdsgjsfk.vision.ui.FaceCheckActivity;
import com.qdsgjsfk.vision.util.Cn2Spell;
import com.qdsgjsfk.vision.util.NetUtil;
import com.rest.business.RestProxy;
import com.rest.response.CollectStudentResponse;
import com.rest.response.Student;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import net.sourceforge.pinyin4j.PinyinHelper;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import cn.wj.android.colorcardview.CardView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import com.qdsgjsfk.vision.base.BaseFragment;
import com.qdsgjsfk.vision.ui.FaceDetectorInfoActivity;

/**
 * Created by HP on 2018/10/6.
 */

public class CollectStudentListFragment extends BaseFragment {

    @BindView(R.id.recyclerView_student_list)
    RecyclerView recyclerView_student_list;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;

    @BindView(R.id.recyclerView_letter)
    RecyclerView recyclerView_letter;

    @BindView(R.id.className)
    TextView className;

    @BindView(R.id.status)
    TextView tv_status;

    List<Student> list = new ArrayList<>();
    List<Student> listWithLetter = new ArrayList<>();
    List<Student> listLetter = new ArrayList<>();

    private String taskId, classId;
    private String type;

    MyAdapter myAdapter;
    MyLetterAdapter myLetterAdapter;

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_student_list;
    }

    @Override
    protected void initView() {
        myAdapter = new MyAdapter();
        recyclerView_student_list.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView_student_list.setAdapter(myAdapter);
        myLetterAdapter = new MyLetterAdapter();
        recyclerView_letter.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView_letter.setAdapter(myLetterAdapter);
        refreshLayout.setRefreshFooter(new BallPulseFooter(getActivity()).setSpinnerStyle(SpinnerStyle.Scale));
        refreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()));
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshlayout -> getStudentList(type));
        refreshLayout.setOnLoadMoreListener(refreshlayout -> {

        });

    }

    @Override
    protected void initData() {
        classId = getArguments().getString("classId");
        type = getArguments().getString("type");
        taskId = getArguments().getString("taskId");
    }


    @Override
    public void onResume() {
        super.onResume();
        getStudentList(type);
    }

    public static CollectStudentListFragment newInstance(String type, String classId, String taskId) {
        Bundle args = new Bundle();
        args.putString("type", type);
        args.putString("classId", classId);
        args.putString("taskId", taskId);
        CollectStudentListFragment fragment = new CollectStudentListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == 1) {//1 首字母  0学生
                return new LetterHolder(getLayoutInflater().inflate(R.layout.item_letter, parent, false));
            } else if (viewType == 0) {
                return new StudentHolder(getLayoutInflater().inflate(R.layout.item_collect_student, parent, false));
            }
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            if (holder instanceof LetterHolder) {
                ((LetterHolder) holder).tv_name.setText(listWithLetter.get(position).letter);
            }
            if (holder instanceof StudentHolder) {
                if (listWithLetter.get(position - 1).type == 1) {
                    if (listWithLetter.size() <= position + 1) {
                        ((StudentHolder) holder).container.setBackgroundResource(R.drawable.round_white);
                        ((StudentHolder) holder).line.setVisibility(View.GONE);
                    } else {
                        if (listWithLetter.get(position + 1).type == 1) {
                            ((StudentHolder) holder).container.setBackgroundResource(R.drawable.round_white);
                            ((StudentHolder) holder).line.setVisibility(View.GONE);
                        } else {
                            ((StudentHolder) holder).container.setBackgroundResource(R.drawable.round_white_top);
                            ((StudentHolder) holder).line.setVisibility(View.VISIBLE);
                        }
                    }
                } else {
                    if (listWithLetter.size() <= position + 1) {
                        ((StudentHolder) holder).container.setBackgroundResource(R.drawable.round_white_bottom);
                        ((StudentHolder) holder).line.setVisibility(View.GONE);
                    } else {
                        if (listWithLetter.get(position + 1).type == 1) {
                            ((StudentHolder) holder).container.setBackgroundResource(R.drawable.round_white_bottom);
                            ((StudentHolder) holder).line.setVisibility(View.GONE);
                        } else {
                            ((StudentHolder) holder).container.setBackgroundColor(getResources().getColor(R.color.white));
                            ((StudentHolder) holder).line.setVisibility(View.VISIBLE);
                        }
                    }
                }

                ((StudentHolder) holder).tv_name.setText(listWithLetter.get(position).studentName + "  " + listWithLetter.get(position).birth);
                if (listWithLetter.get(position).isFinish == 0) {
                    ((StudentHolder) holder).tv_status.setText("未采集");
                    ((StudentHolder) holder).tv_status.setTextColor(Color.parseColor("#F54C4C"));
                } else {
                    ((StudentHolder) holder).tv_status.setText("已采集");
                    ((StudentHolder) holder).tv_status.setTextColor(Color.parseColor("#3EBFC7"));
                }

                ((StudentHolder) holder).itemView.setOnClickListener(v -> {
                    if (listWithLetter.get(position).isFinish == 1) {
                        Bundle bundle = new Bundle();
                        bundle.putString("studentId", listWithLetter.get(position).studentId);
                        bundle.putString("studentName", listWithLetter.get(position).studentName);
                        bundle.putString("faceImg", listWithLetter.get(position).faceImg);
                        bundle.putInt("type", 1);
                        startActivity(FaceCheckActivity.class, bundle);
                    } else {
                        Bundle bundle = new Bundle();
                        bundle.putString("studentId", listWithLetter.get(position).studentId);
                        bundle.putString("studentName", listWithLetter.get(position).studentName);
                        startActivity(FaceDetectorInfoActivity.class, bundle);
                    }
                });

            }

        }

        @Override
        public int getItemCount() {
            return listWithLetter.size();
        }

        @Override
        public int getItemViewType(int position) {
            if (listWithLetter.get(position).type == 1) {
                return 1;
            } else {
                return 0;
            }
        }

        class StudentHolder extends RecyclerView.ViewHolder {
            TextView tv_name, tv_status;
            CardView container;
            View line;

            public StudentHolder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.tv_name);
                container = itemView.findViewById(R.id.container);
                tv_status = itemView.findViewById(R.id.tv_status);
                line = itemView.findViewById(R.id.line);
//                examinationDate = itemView.findViewById(R.id.examinationDate);

            }
        }

        class LetterHolder extends RecyclerView.ViewHolder {
            TextView tv_name;

            public LetterHolder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.tv_name);
            }
        }
    }

    private void getStudentList(String status) {
        System.out.println(classId + "  bbbbbbbbbbbbb");
        System.out.println(taskId + "  cccccccccccccc");
        RestProxy.getInstance().getCollectStudentList(status, "", taskId, classId, new Observer<CollectStudentResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(CollectStudentResponse collectStudentResponse) {
                className.setText(collectStudentResponse.data.desc);
                tv_status.setText(collectStudentResponse.data.studentDesc);
                for (Student s : collectStudentResponse.data.pageInfo.list) {
                    try {
                        s.pinyin = Cn2Spell.getPinYin(s.studentName.trim());
                        s.letter = s.pinyin.substring(0, 1).toUpperCase();
                        if (!s.letter.matches("[A-Z]")) {
                            s.letter = "#";
                        }
                    } catch (Exception e) {
                        s.letter = "#";
                    }
                }
                list.clear();
                list.addAll(collectStudentResponse.data.pageInfo.list);
                Collections.sort(list);
                listWithLetter();
                refreshLayout.finishRefresh();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                refreshLayout.finishRefresh();
                NetUtil.onError(e, mContext);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void listWithLetter() {
        listWithLetter.clear();
        listLetter.clear();
        for (int i = 0; i < list.size(); i++) {
            if (i == 0) {
                Student stu = new Student();
                stu.letter = list.get(0).letter;
                stu.type = 1;
                listWithLetter.add(stu);
                listWithLetter.add(list.get(0));
                listLetter.add(stu);
            } else if (listWithLetter.get(listWithLetter.size() - 1).letter.equals(list.get(i).letter)) {
                listWithLetter.add(list.get(i));
            } else {
                Student stu = new Student();
                stu.letter = list.get(i).letter;
                stu.type = 1;
                listWithLetter.add(stu);
                listWithLetter.add(list.get(i));
                listLetter.add(stu);
            }
        }
        myAdapter.notifyDataSetChanged();
        myLetterAdapter.notifyDataSetChanged();
    }


    class MyLetterAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new LetterHolder(getLayoutInflater().inflate(R.layout.item_right_letter, parent, false));
        }

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
            ((LetterHolder) holder).tv_name.setText(listLetter.get(position).letter);
            if (listLetter.get(position).rightLetterChoose == 1) {
                ((LetterHolder) holder).tv_name.setTextColor(getResources().getColor(R.color.white));
                ((LetterHolder) holder).tv_name.setBackgroundResource(R.drawable.circle_blue);
            } else {
                ((LetterHolder) holder).tv_name.setTextColor(getResources().getColor(R.color.commonBlack));
                ((LetterHolder) holder).tv_name.setBackgroundColor(Color.parseColor("#00000000"));
            }
            holder.itemView.setOnClickListener(v -> {

                for (int i = 0; i < listWithLetter.size(); i++) {
                    if (listWithLetter.get(i).type == 1 && listWithLetter.get(i).letter.equals(listLetter.get(position).letter)) {
                        smoothMoveToPosition(recyclerView_student_list, i);
                        break;
                    }
                }

                for (Student stu : listLetter) {
                    stu.rightLetterChoose = 0;
                }
                listLetter.get(position).rightLetterChoose = 1;
                notifyDataSetChanged();
            });

        }

        @Override
        public int getItemCount() {
            return listLetter.size();
        }


        class LetterHolder extends RecyclerView.ViewHolder {
            TextView tv_name;

            public LetterHolder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.tv_name);
            }
        }
    }


    private boolean mShouldScroll;
    //记录目标项位置
    private int mToPosition;

    /**
     * 滑动到指定位置
     */
    private void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) {
        // 第一个可见位置
        int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
        // 最后一个可见位置
        int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));
        if (position < firstItem) {
            // 第一种可能:跳转位置在第一个可见位置之前
            mRecyclerView.smoothScrollToPosition(position);
        } else if (position <= lastItem) {
            // 第二种可能:跳转位置在第一个可见位置之后
            int movePosition = position - firstItem;
            if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
                int top = mRecyclerView.getChildAt(movePosition).getTop();
                mRecyclerView.smoothScrollBy(0, top);
            }
        } else {
            // 第三种可能:跳转位置在最后可见项之后
            mRecyclerView.smoothScrollToPosition(position);
            mToPosition = position;
            mShouldScroll = true;
        }
    }
}
